package com.example.se.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.se.common.BaseResponse;
import com.example.se.common.ErrorCode;
import com.example.se.common.utils.ResultUtils;
import com.example.se.entity.Comment;
import com.example.se.entity.Post;
import com.example.se.entity.Student;
import com.example.se.entity.dto.DeleteRequest;
import com.example.se.entity.dto.PageRequest;
import com.example.se.entity.dto.PostRequest;
import com.example.se.entity.dto.PostVO;
import com.example.se.mapper.StudentMapper;
import com.example.se.service.CommentService;
import com.example.se.service.PostService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import sun.plugin.com.event.COMEventHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RequestMapping("/post")
@RestController
public class PostController {

    public static String USER_LOGIN_STATE = "userLoginState";

    @Resource
    private PostService postService;

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private CommentService commentService;

    /**
     * 发布帖子
     * @param postRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @CrossOrigin
    public BaseResponse<Long> addPost(@RequestBody PostRequest postRequest, HttpServletRequest request){
        if (postRequest == null) {
            System.out.println("参数为空");
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        Post post = new Post();
        BeanUtils.copyProperties(postRequest,post);

        //校验
        String content = post.getContent();
        String title = post.getTitle();
        if (StringUtils.isNotBlank(title) && title.length() > 512){
            return ResultUtils.error(40000,"没有标题或标题过长");
        }

        if (StringUtils.isNotBlank(content) && content.length() > 512){
            return ResultUtils.error(40000,"没有内容或内容过长");
        }

        Student loginUser = getLoginUser(request);
        if (loginUser == null) {
            System.out.println("未登录");
            return ResultUtils.error(ErrorCode.FORBIDDEN_ERROR);
        }
        post.setUserId(loginUser.getId());
        boolean result = postService.save(post);
        if (!result) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR);
        }

        long newPostId = post.getId();
        return ResultUtils.success(newPostId);
    }

    /**
     * 删除帖子
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("delete")
    @CrossOrigin
    public BaseResponse<Boolean> deletePost(@RequestBody DeleteRequest deleteRequest,HttpServletRequest request){
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        Student loginUser = getLoginUser(request);
        if (loginUser == null) {
            System.out.println("未登录");
            return ResultUtils.error(ErrorCode.FORBIDDEN_ERROR);
        }

        Long postId = deleteRequest.getId();
        Post oldPost = postService.getById(postId);
        //判断是否存在
        if (oldPost == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        //仅本人可删除
        if (!oldPost.getUserId().equals(loginUser.getId())) {
            System.out.println("无删除权限");
            return ResultUtils.error(40001,"无权限");
        }

        boolean result = false;
        boolean remove = false;
        try {
            result = postService.removeById(oldPost.getId());

            //还需要删除相关的评论
            QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("post_id",oldPost.getId());
            int count = commentService.count(queryWrapper);
            if (count > 0) {
                remove = commentService.remove(queryWrapper);
            } else {
                remove = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtils.success(result && remove);

    }


    /**
     *获取帖子列表
     * @param request
     * @return
     */
    @GetMapping("/list")
    @CrossOrigin
    public BaseResponse<List<PostVO>> listPost(HttpServletRequest request) {
        Student loginUser = getLoginUser(request);
        if (loginUser == null) {
            return ResultUtils.error(ErrorCode.FORBIDDEN_ERROR);
        }
        List<Post> postList = postService.list();

        //查询帖子评论
        List<PostVO> postVOList = postList.stream().map(post -> {
            PostVO postVO = new PostVO();
            BeanUtils.copyProperties(post, postVO);
            QueryWrapper<Comment> queryWrapper = new QueryWrapper();
            queryWrapper.eq("post_id", post.getId()).orderByDesc("update_time");
            List<Comment> commentList = commentService.list(queryWrapper);
            postVO.setCommentList(commentList);
            return postVO;
        }).collect(Collectors.toList());

        return ResultUtils.success(postVOList);
    }


    /**
     * 分页获取列表
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    @CrossOrigin
    public BaseResponse<Page<PostVO>> listPostByPage(PageRequest pageRequest,HttpServletRequest request) {
        Student loginUser = getLoginUser(request);
        if (loginUser == null) {
            return ResultUtils.error(ErrorCode.FORBIDDEN_ERROR);
        }
        long current = pageRequest.getCurrent();
        long size = pageRequest.getSize();
        QueryWrapper<Post> queryWrapper = new QueryWrapper<>();
        Page<Post> postPage = postService.page(new Page<>(current, size), queryWrapper);

        Page<PostVO> postVOPage = new Page<>();

        // 设置当前页和每页大小
        postVOPage.setCurrent(postPage.getCurrent());
        postVOPage.setSize(postPage.getSize());
        // 设置总记录数
        postVOPage.setTotal(postPage.getTotal());

        // 将 Post 转换为 PostVO 并设置到记录列表中
        List<PostVO> postVOList = new ArrayList<>();
        for (Post post : postPage.getRecords()) {
            PostVO postVO = new PostVO();
            BeanUtils.copyProperties(post,postVO);
            Long postId = post.getId();
            QueryWrapper<Comment> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("post_id",postId).orderByDesc("update_time");
            List<Comment> commentList = commentService.list(queryWrapper1);
            postVO.setCommentList(commentList);
            postVOList.add(postVO);
        }
        // 设置记录列表
        postVOPage.setRecords(postVOList);

        return ResultUtils.success(postVOPage);
    }


    public Student getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        Student currentUser = (Student) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            System.out.println("------未登录------");
            return null;
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        currentUser = studentMapper.selectById(userId);
        if (currentUser == null) {
            System.out.println("------未登录------");
            return null;
        }
        return currentUser;
    }
}
